package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Component
@Slf4j
public class OrdersTask {

    @Autowired
    private OrdersMapper ordersMapper;

    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {//订单超时处理
        log.info("订单超时处理实验！");
        //查询所有数据库中订单状态为待支付 且 下单时间<现在时间-15分钟
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> orders = ordersMapper.getOrdersByStatusandTimeTL(Orders.PENDING_PAYMENT, time);


        if (orders!=null && !orders.isEmpty()) {
            orders.forEach(a -> {
                Orders build = Orders.builder()
                        .id(a.getId())
                        .status(Orders.CANCELLED)
                        .rejectionReason("支付超时，订单取消")
                        .cancelTime(LocalDateTime.now())
                        .build();
                log.info("订单支付超时，现在修改数据库叮当状态取消");
                ordersMapper.update(build);
            });
        }else{
           log.info("没有超时的订单！");
        }

    }

    //每天1点处理前一天没收点击完成的订单
    @Scheduled(cron = "0 15 20 * * ?")
    public void setAllOrdersStatusToOver(){
        log.info("处理未点击完成的订单！");
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(60);
        List<Orders> ordersList = ordersMapper.getOrdersByStatusandTimeTL(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        ordersList.forEach(a->{
            a.setStatus(Orders.COMPLETED);
            a.setDeliveryTime(LocalDateTime.now());
            ordersMapper.update(a);
        });
    }

}
